package com.rms.recruit_management_system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rms.recruit_management_system.mapper.PositionsMapper;
import com.rms.recruit_management_system.pojo.Positions;
import com.rms.recruit_management_system.service.PositionsService;
import com.rms.recruit_management_system.utils.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class PositionsServiceImpl extends ServiceImpl<PositionsMapper,Positions> implements PositionsService {

    @Autowired
    private PositionsMapper positionsMapper;

    /**
     * 添加职位信息
     * @param positions
     */
    @Override
    public void addPositions(Positions positions) {
        positions.setCreateTime(LocalDateTime.now());
        positions.setUpdateTime(LocalDateTime.now());
        positionsMapper.insert(positions);
    }

    /**
     * 删除职位信息
     * @param positionId
     */
    @Override
    public void deletePositions(Integer positionId) {
        positionsMapper.deleteById(positionId);
    }

    /**
     * 更新职位信息
     * @param positions
     */
    @Override
    public void updatePositions(Positions positions) {
        positions.setUpdateTime(LocalDateTime.now());
        positionsMapper.updateById(positions);
    }

    /**
     * 批量删除职位信息
     * @param positionIds
     */
    @Override
    public void batchDeletePositions(List<Integer> positionIds) {
        QueryWrapper<Positions> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("position_id", positionIds);
        positionsMapper.delete(queryWrapper);
    }

    // 分页查询职位信息
    @Override
    public IPage<Positions> getPositionsPage(int pageNum, int pageSize, String search) {
        Page<Positions> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Positions> wrapper = Wrappers.<Positions>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Positions::getPositionName, search).or().like(Positions::getDegreeRequirement, search)
                    .or().like(Positions::getWorkExperience, search).or().like(Positions::getSalary, search)
                    .or().like(Positions::getDepartmentName, search);
        }
        return positionsMapper.selectPage(page, wrapper);
    }

    // 导出职位信息到Excel
    @Override
    public void exportPositionsToExcel(HttpServletResponse response) {
        // 获取所有职位信息
        List<Positions> list = positionsMapper.selectList(null);

        // 加载Excel模板
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/职位表模版.xlsx");
        if (in == null) {
            // 如果模板文件未找到，设置响应状态并返回
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 使用try-with-resources确保资源自动关闭
        try (XSSFWorkbook workbook = new XSSFWorkbook(in);
             ServletOutputStream outputStream = response.getOutputStream()) {

            XSSFSheet sheet = workbook.getSheet("Sheet1");
            if (sheet == null) {
                // 如果Sheet1不存在，创建一个新的Sheet
                sheet = workbook.createSheet("Sheet1");
            }

            int rowNum = 1; // 数据从第2行开始写入（第1行通常是标题）
            for (Positions positions : list) {
                // 如果当前行不存在，则创建新行
                XSSFRow row = sheet.getRow(rowNum);
                if (row == null) {
                    row = sheet.createRow(rowNum);
                }

                // 设置每个单元格的值
                row.createCell(0).setCellValue(positions.getPositionName());
                row.createCell(1).setCellValue(positions.getPositionDescription());
                row.createCell(2).setCellValue(positions.getDegreeRequirement());
                row.createCell(3).setCellValue(positions.getWorkExperience());
                row.createCell(4).setCellValue(positions.getSalary());
                row.createCell(5).setCellValue(positions.getDepartmentName());

                rowNum++; // 移动到下一行
            }

            // 设置响应头信息
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=职位表.xlsx");

            // 将工作簿写入输出流
            workbook.write(outputStream);

        } catch (IOException e) {
            // 处理IO异常，可以记录日志或返回错误信息
            e.printStackTrace();
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出Excel失败");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

    }

    /**
     * 根据学历要求查询职位信息
     * @param degree
     * @return
     */
    @Override
    public List<Positions> getPositionsByDegree(String degree) {
        return positionsMapper.selectList(new QueryWrapper<Positions>().eq("degree_requirement",degree));
    }

    /**
     * 根据职位ID查询职位信息
     * @param positionId
     * @return
     */
    @Override
    public Positions getPositionsById(Integer positionId) {
        return positionsMapper.selectById(positionId);
    }

    @Override
    public Integer getPositionsCount() {
        return Math.toIntExact(positionsMapper.selectCount(null));
    }

    /**
     * 获取职位被投递数量前五的职位信息
     * @return
     */
    @Override
    public List<Positions> getPositionsSubmitCount() {
        QueryWrapper<Positions> wrapper=new QueryWrapper<>();
        wrapper.select("position_name","submit_quantity").ne("submit_quantity",0).orderByDesc("submit_quantity").last("limit 5");
        return positionsMapper.selectList(wrapper);
    }

}


